package com.wujie.hello.spring.cloud.alibaba.nacos.rest.consumer.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wujie
 * @version 1.0.0:
 * @title TokenInterceptor
 * @Description TODO RestTemplate调用其他服务的时候会出现丢失token的情况，所以自定义一个拦截器，将token加入请求头
 *              TODO 并在初始化RestTemplate的时候配置好拦截器
 * @dateTime 2020/9/10 16:43
 * @Copyright 2020-2021
 */
@Component
public class TokenInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        HttpHeaders headers = request.getHeaders();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)auth.getDetails();

        // 加入自定义字段
        headers.add("Authorization", details.getTokenType() + " " + details.getTokenValue());

        // 保证请求继续被执行
        return execution.execute(request, body);
    }

}
